package com.think.utils;

import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import jodd.exception.ExceptionUtil;
import jodd.mail.Email;
import jodd.mail.EmailAttachmentBuilder;
import jodd.mail.SendMailSession;
import jodd.mail.SmtpServer;
import jodd.mail.SmtpSslServer;

import com.google.common.base.Throwables;

/**
 * @description	<pre>
 * 发送邮件工具类
 * tips：
 * 	在通过 JavaMail 使用 163 邮箱发邮件时有几点问题需要注意。
	550 用户被锁定：普通 163 邮箱是无法通过 smtp.163.com 发送邮件的，只有 163 VIP 邮箱才行，然后设置 mail.smtp.host=smtp.vip.163.com
	454 Command not permitted when TLS active：需要设置 mail.smtp.starttls.enable=false
	553 authentication is required：需要设置 mail.smtp.auth=true
	550 Invalid User：from 必须写成带 @ 的邮件格式，且 username 要用 @ 前面的
	在使用qq邮箱时，注意：
	要先去配置开启邮件客户端，拿到授权码作为密码，并且要使用ssl登录
 *	</pre>
 * @author	dzy
 * @date	2016年8月16日
 */
@SuppressWarnings("all")
public class EmailKit {
    public static final Integer PRIORITY_HIGHEST = 1;
    public static final Integer PRIORITY_NORMAL = 2;
    public static final Integer PRIORITY_LOW = 3;

    public static final String DEFAULT_ENCODING = "UTF-8";
    
    protected static Logger logger = LoggerFactory.getLogger(EmailKit.class);
    

    /**
     * 创建一个简单的Email对象
     *
     * @param from
     * @param to
     * @param subject
     * @param text
     * @param html
     * @return
     */
    public static Email createBaseEmail(String from, String to, String subject, String text, String html) {
        Email email = Email.create()
                .from(from)
                .to(to)
                .subject(subject, DEFAULT_ENCODING)
                .addText(text, DEFAULT_ENCODING)
                .addHtml(html, DEFAULT_ENCODING);
        return email;
    }

    /**
     * 带附件的简单邮件模版
     *
     * @param from
     * @param to
     * @param subject
     * @param text
     * @param html
     * @param attachmentBuilder
     * @return
     */
    public static Email createBaseEmail(String from, String to, String subject, String text, String html, EmailAttachmentBuilder attachmentBuilder) {
        Email email = Email.create()
                .from(from)
                .to(to)
                .subject(subject, DEFAULT_ENCODING)
                .addText(text, DEFAULT_ENCODING)
                .addHtml(html, DEFAULT_ENCODING);
        if (null != attachmentBuilder) {
            email.attach(attachmentBuilder);
        }
        return email;
    }

    /**
     * 发送一封邮件
     *
     * @param host         host，如smtp.qq.com
     * @param hostUser     邮箱帐号
     * @param hostPassWord 邮箱密码
     * @param email        要发送邮件文档对象
     * @return
     */
    public static String sendMail(String host, String hostUser, String hostPassWord, Boolean useSSL, Email email) {
        String msgId = null;
        SendMailSession session = null;
        try {
            SmtpServer smtpServer;
            if (useSSL) {
            	smtpServer = SmtpSslServer.create(host).property("mail.smtp.starttls.enable","false").authenticateWith(hostUser, hostPassWord);
            } else {
            	smtpServer = SmtpServer.create(host).authenticateWith(hostUser, hostPassWord);
            }
            session = smtpServer.createSession();
            session.open();
            msgId = session.sendMail(email);
        } catch (Exception e) {
        	logger.error("sendMail-ex:{}", Throwables.getStackTraceAsString(e));
            throw Throwables.propagate(e);
        } finally {
            session.close();
            return msgId;
        }
    }
    /**
     * 发送一封邮件
     *
     * @param host         host，如smtp.qq.com
     * @param hostUser     邮箱帐号
     * @param hostPassWord 邮箱密码
     * @param email        要发送邮件文档对象
     * @return
     */
    public static String sendMail(String host,int port, String hostUser, String hostPassWord, Boolean useSSL, Email email) {
    	String msgId = null;
    	SendMailSession session = null;
    	try {
    		SmtpServer smtpServer;
    		if (useSSL) {
    			smtpServer = SmtpSslServer.create(host,port).authenticateWith(hostUser, hostPassWord);
    		} else {
    			smtpServer = SmtpServer.create(host,port).authenticateWith(hostUser, hostPassWord);
    		}
    		session = smtpServer.createSession();
    		session.open();
    		msgId = session.sendMail(email);
    	} catch (Throwable t) {
    		logger.error("sendMail-ex:{}", t);
    		throw Throwables.propagate(t);
    	} finally {
    		session.close();
    		return msgId;
    	}
    }
}
